package com.sjzd.meeting.controller.admin;

import com.sjzd.meeting.pojo.AdminUser;
import com.sjzd.meeting.service.IAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("/admin")
public class AdminUserController {

    @Autowired
    private IAdminUserService adminUserService;

    /**
     *  跳转至登录页面
     * @return
     */
    @GetMapping("/login")
    public String login() {
        return "admin/login";
    }

    /**
     *  登录验证操作
     * @param username
     * @param password
     * @param req
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletRequest req, Model model) {
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            AdminUser admin = adminUserService.login(username, password);
            System.out.println(admin.toString());
            if (null != admin) {
                if (null == admin.getLoginCount() || // 第一次登录
                        StringUtils.isEmpty(admin.getLoginCount())) {
                    admin.setLoginCount("1");
                    req.getSession().setAttribute("admin", admin);
                } else {
                    req.getSession().setAttribute("admin", admin);
                    long lastCount = Long.parseLong(admin.getLoginCount());
                    admin.setLoginCount( "" + Long.parseLong("" + lastCount));
                }
                admin.setLastLoginTime(new Date());
                admin.setLastIp(req.getRemoteAddr());
                int flag = adminUserService.update(admin);
                if (flag == 0) {
                    model.addAttribute("message", "服务器繁忙请稍后重试！");
                    req.getSession().removeAttribute("admin");
                    return "admin/login";
                }
                return "admin/index";
            }
        }
        model.addAttribute("message","用户名或密码错误");
        return "admin/login";
    }
}
